package com.atguigu.test;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class test_es_08_doc_bulk_create {

    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));

        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.add(new IndexRequest("user").id("1001").source(XContentType.JSON,"name","zhangsan", "age",20,"sex","男"));
        bulkRequest.add(new IndexRequest("user").id("1002").source(XContentType.JSON,"name","wangwu", "age",30,"sex","男"));
        bulkRequest.add(new IndexRequest("user").id("1003").source(XContentType.JSON,"name","wangwu1", "age",20,"sex","女"));
        bulkRequest.add(new IndexRequest("user").id("1004").source(XContentType.JSON,"name","zhangsan1", "age",30,"sex","男"));
        bulkRequest.add(new IndexRequest("user").id("1005").source(XContentType.JSON,"name","zhangsan2", "age",40,"sex","女"));
        bulkRequest.add(new IndexRequest("user").id("1006").source(XContentType.JSON,"name","zhangsan12", "age",50,"sex","女"));
        bulkRequest.add(new IndexRequest("user").id("1007").source(XContentType.JSON,"name","zhangsan123", "age",10,"sex","男"));
        bulkRequest.add(new IndexRequest("user").id("1008").source(XContentType.JSON,"name","liliu", "age",10,"sex","男"));

        //批量添加、发送请求
        BulkResponse response = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(response.getTook());
        System.out.println(response.getItems());
        BulkItemResponse[] items = response.getItems();
        for (int i = 0; i < items.length; i++) {
            System.out.println(items[i].getResponse());
        }

        //关闭es客户端
        esClient.close();;

    }
}
